<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\data\material\stat;

use app\model\mongo\MongoMaterialSyncLogModel;
use app\model\mongo\MongoStatModel;
use app\service\analysis\AnalysisService;
use app\service\analysis\report\ReportService;
use think\Model;

trait DayStatTrait
{
    /**
     * @var null|ReportService 报表数据
     */
    protected ?ReportService $reportService;

    /**
     * @var null|Model 数据模型
     */
    protected ?Model $material;

    /**
     * @var string 素材MD5签名
     */
    protected string $signature;

    /**
     * @var int 媒体类型
     */
    protected int $mediaId;

    /**
     * @var int 汇总日期
     */
    protected int $statDate;

    public function setStat(): bool
    {
        if (! $this->setReport()) {
            return false;
        }

        if (! $this->setMaterial()) {
            return false;
        }

        if ($this->material->getKey()) {
            if (! $this->setDayStat()) {
                return false;
            }
        }

        return true;
    }

    /**
     * 设置日汇总数据.
     */
    private function setDayStat(): bool
    {
        $model = $this->getDayStatModel();
        if (! $model instanceof MongoStatModel) {
            return self::setError('未知素材日汇总模型');
        }
        if (! $model->getKey()) {
            $data = [
                'stat_date' => $this->statDate,
                'stat_month' => intval(date('Ym', strtotime(strval($this->statDate)))),
                'signature' => $this->signature,
                'area_id' => $this->material->getAttr('area_id'),
                'qq' => ['cost' => 0],
                'oe' => ['cost' => 0],
                'ks' => ['cost' => 0],
                'is_change' => MongoStatModel::IS_CHANGE_YES,
            ];
        } else {
            $data = [
                'is_change' => MongoStatModel::IS_CHANGE_YES,
            ];
        }
        $data = $this->getDayStatField($data);
        $model->setAttrs($data);
        if (! $model->save()) {
            return self::setError('保存日维度汇总失败');
        }
        return true;
    }

    /**
     * 获取日汇总字段值
     * @param array $data 更新数据
     */
    private function getDayStatField(array $data = []): array
    {
        $mediaName = strtolower(AnalysisService::getTablePrefix($this->mediaId));
        // 消耗查询
        $map = [
            ['signature', '=', $this->signature],
            ['stat_date', '=', $this->statDate],
        ];
        $data[$mediaName]['cost'] = $this->reportService::getSignatureCost($map);

        return $data;
    }
}
